package io.yyxx.boot.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.yyxx.boot.business.entity.billDataEntity.BillQueryParams;
import io.yyxx.boot.business.entity.time.SyncTimestamp;
import io.yyxx.boot.business.mapper.SyncTimestampMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 数据同步服务
 */
@Service
@Slf4j
public class DataSyncService {

    // 时间格式（年-月-日）
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Resource
    SyncTimestampMapper syncTimestampMapper;

    @Resource
    FlightBillDataServiceImpl flightBillDataServiceImpl;

    @Resource
    CarBillDataServiceImpl carBillDataServiceImpl;

    @Resource
    HotelBillDataServiceImpl hotelBillDataServiceImpl;

    @Resource
    TrainBillDataServiceImpl trainBillDataServiceImpl;

    /**
     * 执行完整同步流程(第三方向数据库进行同步)
     */
    public void syncDataProcess(BillQueryParams params, String appKey, String corpToken) {

        // 1. 获取上次同步时间
        String lastSyncTime = getLastSyncTime();


        // 3. 处理业务数据,将初始数据或更新之后的数据保存到数据库
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(4);
        // 提交任务到线程池
        executor.submit(() -> flightBillDataServiceImpl.saveToDatabase(params, appKey, corpToken));
        executor.submit(() -> carBillDataServiceImpl.saveToDatabase(params, appKey, corpToken));
        executor.submit(() -> hotelBillDataServiceImpl.saveToDatabase(params, appKey, corpToken));
        executor.submit(() -> trainBillDataServiceImpl.saveToDatabase(params, appKey, corpToken));

        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            log.error("第三方向数据库进行同步时,线程池关闭失败,强制关闭", e);
        }

        log.info("已执行完所有（第三方向数据库进行同步时）的线程任务");
        // 4. 更新同步时间戳
        updateSyncTimestamp(LocalDateTime.now());
    }

    /**
     * 获取最后同步时间
     */
    private String getLastSyncTime() {
        // 使用MyBatis-Plus的条件构造器
        QueryWrapper<SyncTimestamp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("last_time", "last_sync_time");

        SyncTimestamp timestamp = syncTimestampMapper.selectOne(queryWrapper);

        if (timestamp != null) {
            return timestamp.getValue();
        } else {
            // 初始化时间戳
            String initTime = "1970-01-01";
            SyncTimestamp newTimestamp = new SyncTimestamp();
            newTimestamp.setLastTime("last_sync_time");
            newTimestamp.setValue(initTime);
            newTimestamp.setUpdateTime(LocalDateTime.now());
            syncTimestampMapper.insert(newTimestamp);
            return initTime;
        }
    }

    /**
     * 更新时间戳记录
     */
    private void updateSyncTimestamp(LocalDateTime timestamp) {
        // 格式化时间
        String formattedTime = timestamp.format(DATE_FORMATTER);

        // 构造更新对象
        SyncTimestamp updateEntity = new SyncTimestamp();
        updateEntity.setLastTime("last_sync_time");
        updateEntity.setValue(formattedTime);
        updateEntity.setUpdateTime(LocalDateTime.now());

        // 使用MyBatis-Plus的插入或更新
        QueryWrapper<SyncTimestamp> wrapper = new QueryWrapper<>();
        wrapper.eq("last_time", "last_sync_time");

        if (syncTimestampMapper.exists(wrapper)) {
            syncTimestampMapper.update(updateEntity, wrapper);
        } else {
            syncTimestampMapper.insert(updateEntity);
        }
    }
}